from appium.webdriver import WebElement
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException, ElementClickInterceptedException
from utils.log_utils import log
from selenium.webdriver.support.select import Select
from core.driver_factory import DriverFactory  # 引入工厂类

class BasePage:
    # 初始化浏览器驱动（通过DriverFactory）
    def __init__(self, driver=None):
        if driver is None:
            self.driver = DriverFactory.get_driver()  # 使用工厂类获取驱动
            # 最大化窗口
            self.driver.maximize_window()
            # 隐式等待
            self.driver.implicitly_wait(10)
        else:
            self.driver = driver

    def open_url(self, url):
        """打开指定URL"""
        self.driver.get(url)
        return self  # 链式调用支持


    # 封装find_element（元素定位，支持显式等待）
    def find_element(self, locator, timeout=20):
        """
        定位单个元素
        locator: 元组，如(By.ID, "username")
        """
        try:
            element = WebDriverWait(self.driver, timeout).until(
                EC.presence_of_element_located(locator)
            )
            log.info(f"找到元素：{locator}")
            return element
        except TimeoutException:
            log.error(f"超时未找到元素：{locator}")
            raise  # 抛出异常，便于测试用例捕获

    def click(self, locator: tuple) -> None:
        """
        点击元素，优先用原生click，失败则用JavaScript强制点击
        :param locator: 元素定位器 (By.xxx, "value")
        """
        element: WebElement = self.find_element(locator)
        try:
            element.click()  # 优先尝试原生点击
        except ElementClickInterceptedException:
            # 原生点击失败，用JavaScript强制点击
            self.driver.execute_script("arguments[0].click();", element)
            log.warning(f"元素 {locator} 被遮挡，已用JavaScript强制点击")

    def send_keys(self, locator, text):
        """输入文本"""
        self.find_element(locator).send_keys(text)
        log.info(f"向元素{locator}输入：{text}")

    def select_index(self,locator,index):
        """通过索引"""
        a = Select(self.find_element(locator))
        a.select_by_index(index)

    def select_value(self,locator,value):
        """通过value属性"""
        a = Select(self.find_element(locator))
        a.select_by_value(value)

    def select_visible_text(self,locator,text):
        """可见文本"""
        a = Select(self.find_element(locator))
        a.select_by_visible_text(text)

    def get_text(self, locator):
        """获取元素文本"""
        text = self.find_element(locator).text
        log.info(f"元素{locator}的文本为：{text}")
        return text

    def quit(self):
        """关闭浏览器"""
        if self.driver:
            self.driver.quit()
            log.info("关闭浏览器")
